package com.xcms.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class TestFilter implements Filter {

	private String encoding=null;
	public void init(FilterConfig config) throws ServletException {
		
		encoding=config.getInitParameter("encoding");
		System.out.println("获取到的当前的初始化参数编码："+encoding);
	}
	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
//		request.getRequestDispatcher("1.jpg").forward(request, response);
		//request.getRequestDispatcher("/").
		//统一访问请求的编码
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
////		response.setContentType("text/html");
////		response.getWriter().write("<script type='text/javascript'>alert('本次请求完成！！！')</script>");
//		chain.doFilter(request, response);
		HttpServletRequest request2=(HttpServletRequest) request;
		String username=(String) request2.getSession().getAttribute("username");
		String url=request2.getRequestURI();
//		System.out.println("filter2……"+url);
		boolean isContinue=false;
		//通过url 控制访问
		if(username!=null&&username.length()>0||url.endsWith("/login"))
		{
			//登录完成后再去进行一次权限验证
			//举例：只有admin 这个用户才可以访问admin这个目录
			if(url.contains("/amdin/"))//如果当前url 包含admin 目录 就拦截
			{
				//判定是否是admin这个用户
				if(username.equals("admin"))
					isContinue=true;
				else
					isContinue=false;
			}
		}
		//todo:静态资源的方向建议放到数据库，或者列表
		if(url.contains("/login")||url.contains("/member")
				||url.contains("/css")||url.contains("/img")
				||url.endsWith("/")||url.endsWith("/login"))
			isContinue=true;
		if(isContinue)//是否继续往下走
			chain.doFilter(request, response);
		else {
//			if(!url.endsWith("/login"))
//				request2.getSession().setAttribute("lasturl", url);
//			request.setAttribute("error", "对不起，您当前请求的资源要求登录后才可以访问，请登录后重试！！");
//			request.getRequestDispatcher("index.jsp").forward(request, response);
			response.setContentType("text/html");
			response.getWriter().println("权限不足!");
		}
	}


}
